/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
export var findFrequentTreeSum = function (root) {
  const map = new Map()
  function dfs(node) {
    if (!node) return 0
    const sum = node.val + dfs(node.left) + dfs(node.right)
    if (map.has(sum)) map.set(sum, map.get(sum) + 1)
    else map.set(sum, 1)
    return sum
  }
  dfs(root)
  let ans = []
  let max = 0
  for (const key of map.keys()) {
    const cnt = map.get(key)
    if (cnt > max) {
      ans = []
      max = cnt
    }
    if (cnt === max) ans.push(key)
  }
  return ans
}
